package com.xdf.xzymanagementsystem.util;

import org.apache.commons.collections.CollectionUtils;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: xzy-management-system
 * @description: 集合操作
 * @author: 张柯
 * @create: 2021-04-22 18:45
 **/
public class CollectionsUtil {
    private CollectionsUtil() {
    }

    /**
     * 更换集合顺序
     *
     * @param list
     * @param oldPosition
     * @param newPosition
     */
    public static <T> void swapCollection(List<T> list, int oldPosition, int newPosition) {
        if (list == null && list.size() <= 0) return;
        int len = list.size();
        if (oldPosition < 0) oldPosition = 0;
        if (newPosition < 0) newPosition = 0;
        if (oldPosition > len - 1) {
            oldPosition = len - 1;
        }
        if (newPosition > len - 1) {
            newPosition = len - 1;
        }
        if (oldPosition == newPosition) return;
        list.add(newPosition, list.remove(oldPosition));
    }

    /**
     * 更换集合顺序(Float类型)
     *
     * @param list
     * @param oldPosition
     * @param newPosition
     */
    public static <T> void swapFloatCollection(List<T> list, float oldPosition, float newPosition) {
        if (list == null && list.size() <= 0) return;
        int len = list.size();
        if (oldPosition < 0) oldPosition = 0;
        if (newPosition < 0) newPosition = 0;
        if (oldPosition > len - 1) {
            oldPosition = len - 1;
        }
        if (newPosition > len - 1) {
            newPosition = len - 1;
        }
        if (oldPosition == newPosition) return;
        int oldIndex = (int) oldPosition;
        int newIndex = (int) newPosition;
        // 先移除元素
        T element = list.remove(oldIndex);
        // 然后在新位置添加元素
        list.add(newIndex, element);
    }

    /**
     * 排序
     *
     * @param list
     * @param comparator
     * @param <T>
     * @return
     */
    public static <T> List<T> sortBy(List<T> list, Comparator comparator) {
        if (CollectionUtils.isEmpty(list)) return list;
        return (List<T>) list.stream().sorted(Comparator.nullsLast(comparator)).collect(Collectors.toList());
    }
}
